package leetcode;

public class Demo2 {
    public Object object=new Object();
    int num=0;

    public void add(){
        synchronized (object){
            while (num!=0){
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            num++;
            System.out.println(Thread.currentThread().getName()+"\r"+num);
            object.notify();
        }

    }

    public void dre(){
        synchronized (object){
            while (num==0){
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            num--;
            System.out.println(Thread.currentThread().getName()+"\r"+num);
            object.notify();
        }
    }

    public static void main(String[] args) {

        Demo2 demo2=new Demo2();

        for (int i=0;i<5;i++){
            new Thread(()->{
                demo2.add();
            },"aa").start();
        }
        for (int i=0;i<5;i++){
            new Thread(()->{
                demo2.dre();
            },"bb").start();
        }

    }
}
